package com.ruoyi.coffee.service.impl;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.coffee.dto.AddressDto;
import com.ruoyi.coffee.mapper.UsersMapper;
import com.ruoyi.coffee.vo.AddressVo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;

import org.springframework.stereotype.Service;
import com.ruoyi.coffee.mapper.AddressesMapper;
import com.ruoyi.coffee.domain.Addresses;
import com.ruoyi.coffee.service.IAddressesService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 收货地址Service业务层处理
 *
 * @author dxj
 * @date 2025-01-07
 */
@Service
public class AddressesServiceImpl extends ServiceImpl<AddressesMapper, Addresses> implements IAddressesService {
    @Resource
    private AddressesMapper addressesMapper;

    @Resource
    private UsersMapper usersMapper;

    /**
     * 查询收货地址
     *
     * @param id 收货地址主键
     * @return 收货地址
     */
    @Override
    public Addresses selectAddressesById(Long id) {
        return addressesMapper.selectAddressesById(id);
    }

    /**
     * 查询收货地址列表
     *
     * @param addresses 收货地址
     * @return 收货地址
     */
    @Override
    public List<Addresses> selectAddressesList(Addresses addresses) {
        return addressesMapper.selectAddressesList(addresses);
    }

    /**
     * 新增收货地址
     *
     * @param addresses 收货地址
     * @return 结果
     */
    @Override
    public int insertAddresses(Addresses addresses) {
        addresses.setCreateTime(DateUtils.getNowDate());
        return addressesMapper.insertAddresses(addresses);
    }

    /**
     * 修改收货地址
     *
     * @param addresses 收货地址
     * @return 结果
     */
    @Override
    public int updateAddresses(Addresses addresses) {
        addresses.setUpdateTime(DateUtils.getNowDate());
        return addressesMapper.updateAddresses(addresses);
    }

    /**
     * 批量删除收货地址
     *
     * @param ids 需要删除的收货地址主键
     * @return 结果
     */
    @Override
    public int deleteAddressesByIds(Long[] ids) {
        return addressesMapper.deleteAddressesByIds(ids);
    }

    /**
     * 删除收货地址信息
     *
     * @param id 收货地址主键
     * @return 结果
     */
    @Override
    public int deleteAddressesById(Long id) {
        return addressesMapper.deleteAddressesById(id);
    }

    /**
     * 微信用户新增用户地址
     *
     * @param addressDto
     * @return
     */
    @Override
    public AjaxResult saveUserAddress(AddressDto addressDto) {
        Addresses addresses = new Addresses();
        //封装参数
        BeanUtils.copyProperties(addressDto, addresses);
        return AjaxResult.success(baseMapper.insert(addresses));
    }

    /**
     * 查询用户的所有地址
     *
     * @param userId
     * @return
     */
    @Override
    public AjaxResult getAddressesListById(Long userId) {
        LambdaQueryWrapper<Addresses> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.select(Addresses::getId, Addresses::getReceiverName, Addresses::getReceiverPhone, Addresses::getAddress, Addresses::getIsDefault);
        lambdaQuery.eq(Addresses::getUserId, userId);
        //查询对应的用户姓名
        String userName = usersMapper.selectUsersById(userId).getUsername();
        List<AddressVo> addressesList = baseMapper.selectList(lambdaQuery).stream().map(item -> {
            AddressVo addressVo = new AddressVo();
            BeanUtils.copyProperties(item, addressVo);
            addressVo.setUserName(userName);
            return addressVo;
        }).collect(Collectors.toList());
        return AjaxResult.success(addressesList);
    }

    /**
     * 修改用户地址
     *
     * @param addressDto
     * @return
     */
    @Override
    public AjaxResult updateUserAddress(AddressDto addressDto) {
        // 直接使用更新后的对象，避免重复查询
        AddressVo addressVo = new AddressVo();
        try {
            Addresses addresses = new Addresses();
            //封装参数
            BeanUtils.copyProperties(addressDto, addresses);
            //构建修改条件
            LambdaQueryWrapper<Addresses> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(Addresses::getId, addresses.getId())
                    .eq(Addresses::getUserId, addresses.getUserId());
            int updateCount = baseMapper.update(addresses, queryWrapper);
            if (updateCount <= 0) {
                return AjaxResult.error("地址更新失败");
            }
            BeanUtils.copyProperties(addresses, addressVo);
        } catch (Exception e) {
            return AjaxResult.error("地址更新失败");
        }
        return AjaxResult.success(addressVo);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateDefaultAddress(Long addressId, Long userId) {
        //查询出之前的默认地址，把它改为非默认
        LambdaQueryWrapper<Addresses> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Addresses::getUserId, userId)
                          .eq(Addresses::getIsDefault, 1L).select(Addresses::getId);
        Optional<Addresses> optionalAddresses = Optional.ofNullable(baseMapper.selectOne(lambdaQueryWrapper));
        optionalAddresses.ifPresent(oldAddresses -> {
            oldAddresses.setIsDefault(2L);
            int updateOldCount = baseMapper.update(oldAddresses, new LambdaQueryWrapper<Addresses>().eq(Addresses::getId, oldAddresses.getId()));
            if (updateOldCount <= 0) {
                throw new RuntimeException("非默认地址更新失败");
            }
            Addresses addresses = new Addresses();
            //设置为默认地址状态
            addresses.setIsDefault(1L);
            LambdaQueryWrapper<Addresses> lambdaQuery = new LambdaQueryWrapper();
            lambdaQuery.eq(Addresses::getId, addressId)
                    .eq(Addresses::getUserId, userId);
            int updateCount = baseMapper.update(addresses, lambdaQuery);
            if (updateCount <= 0) {
                throw new RuntimeException("非默认地址更新失败");
            }
        });
        return AjaxResult.success();
    }
}

